package com.ck.core.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * 日期工具类
 */
public class DateUtils {
    private static Logger logger = LoggerFactory.getLogger(DateUtils.class);
    public static final String PATTEN_YMD_HMS = "yyyy-MM-dd HH:mm:ss";
    public static final String ZERO_TIME_STRING = "00:00:00";
    public static final String PATTEN_YMD = "yyyy-MM-dd";
    public static final String PATTEN_YMD1 = "yyyy/MM/dd";
    public static final String PATTEN_YMD_HMS1 = "yyyy/MM/dd HH:mm:ss";
    public static final String PATTEN_MD = "MM-dd";
    public static final String PATTEN_YMDHMS = "yyyyMMddHHmmss";
    public static final String PATTEN_YYYYMMDD = "yyyyMMdd";
    public static final String PATTEN_YM = "yyyy-MM";
    public static final String PATTEN_YYYYMM = "yyyyMM";
    public static final String PATTEN_YMD_DEL = "yyyy.MM.dd";
    public static final String PATTEN_YM_DEL = "yyyy.MM";
    /**
     * 把long类型日期转化为格式化字符串日期
     *
     * @param longTimeStamp long类型时间戳
     * @param pattern       格式
     * @return String(格式化后的日期)
     */
    public static String longTimeStampToStringDate(Long longTimeStamp, String pattern) {
        if (longTimeStamp == null || StringUtils.isBlank(pattern)) {
            throw new NullPointerException("时间戳或格式类型不能为空");
        }
        Date date = new Date(longTimeStamp);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String formatDate = simpleDateFormat.format(date);
        return formatDate;
    }

    /**
     * 把字符串日期转换为LonG类型日期
     *
     * @param time    字符串日期
     * @param pattern 格式
     * @return Long日期
     * @throws ParseException
     */
    public static Long stringTimeToLongTimeStamp(String time, String pattern) throws ParseException {
        if (StringUtils.isBlank(time) || StringUtils.isBlank(pattern)) {
            throw new NullPointerException("时间或格式类型不能为空");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Long formateDate = simpleDateFormat.parse(time).getTime();
        return formateDate;
    }

    /**
     * 时间范围转换为开始时间和结束时间
     *
     * @param dateRange 时间范围
     * @return HashMap<Object ,   O bject>
     */
    public static HashMap<Object, Long> dateRangeToString(String dateRange, String pattern) throws ParseException{
        HashMap<Object, Long> resultMap = new HashMap<>(2);
        Long startTime = null;
        Long endTime = null;
        if(StringUtils.isNotBlank(dateRange)) {
            String[] dateRangeArr = dateRange.split("-");
            String startTimeStr = dateRangeArr[0];
            String endTimeStr = dateRangeArr[1];
            if (StringUtils.isNotBlank(startTimeStr)) {
                startTime = stringTimeToLongTimeStamp(startTimeStr, pattern);
                endTime = stringTimeToLongTimeStamp(endTimeStr, pattern);
			}
		}
        resultMap.put("startTime", startTime);
        resultMap.put("endTime", endTime);
        return resultMap;
	}

    /**
     * 获取任意时间下一个月
     *
     * @param dateL 任意时间
     * @return
     */
    public static Long getPreMonth(Long dateL) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dateL);
        cal.add(Calendar.MONTH, 1);
        return cal.getTimeInMillis();
    }

    /**
     * 给定一个时间，获取该时间多少天之后（负数时为多少天之前）的时间
     * @param date
     * @param num
     * @return
     */
    public static Date getNextNumDay(Date date,int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, num);
        return calendar.getTime();
    }

    /**
     * 给定一个时间，获取该时间多少小时之后（负数时为多少小时之前）的时间
     * @param date
     * @param num
     * @return
     */
    public static Date getNextHour(Date date, int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int hour = calendar.get(Calendar.HOUR);
        hour = hour + num;
        calendar.set(Calendar.HOUR, hour);
        return calendar.getTime();
    }


    public static String dateToString(Date date,String pattern) {
        String str = "";
        try {
            if (date != null) {
                SimpleDateFormat formater = new SimpleDateFormat(pattern);
                str = formater.format(date);
            }
        } catch (Exception e) {
            throw e;
        }
        return str;
    }

    /**
     * 获取2个时间相隔几天 "2010-08-01 00:00:00 - 2010-08-03 23:59:59"算三天
     */
    public static int getBetweenDayNumber(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return -1;
        }
        if (startDate.after(endDate)) {
            Date tmp = endDate;
            endDate = startDate;
            startDate = tmp;
        }
        long dayNumber = -1L;
        long day = 24L * 60L * 60L * 1000L;
        try {
            dayNumber = (endDate.getTime() + 1000 - startDate.getTime()) / day;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return (int) dayNumber;
    }

    /**
     * 判断一个日期是否为周末
     * @param date
     * @return
     */
    public static boolean isWeekend(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY
                ||cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
            return true;
        }
        return false;
    }

    /**
     * 获取两个时间之间相隔多少天，多少小时，多少分钟
     * @param startTime
     * @param endTime
     * @return
     */
    public static String getDateDiff(Date startTime,Date endTime){
        if ( startTime == null || endTime == null ) {
            return null;
        }
        return getTimeStampDiff(startTime.getTime(),endTime.getTime());
    }

    /**
     * 获取两个时间戳之间相隔多少天，多少小时，多少分钟
     * @param startTime
     * @param endTime
     * @return
     */
    public static String getTimeStampDiff(Long startTime, Long endTime) {

        if ( startTime == null || endTime == null ) {
            return null;
        }

        //每天毫秒数
        long nd = 1000L * 24 * 60 * 60;
        //每小时毫秒数
        long nh = 1000L * 60 * 60;
        //每分钟毫秒数
        long nm = 1000L * 60;
        // 获得两个时间的毫秒时间差异
        long diff = Math.abs(startTime - endTime);
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;

        return day + "天" + hour + "小时" + min + "分钟";

    }

    /**
     * 获取过去第几天的日期
     *
     * @return String（格式化的时间）
     */
    public static String getPastDay(int past, String pattern) {
        if (pattern == null || pattern == "") {
            throw new IllegalArgumentException("pattern must bu not null");
        }
        // 得到一个Calendar的实例
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String result = format.format(today);
        return result;
    }

    /**
     * 取得一个date对象对应的日期的0点0分0秒时刻的Date对象。
     */
    public static Date getMinDateOfDay(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

}